var ColoredButton = (function () {
    //继承ui.Widget
    util.extend(ColoredButton, ui.Widget);

    function ColoredButton() {
        //调用父类构造函数
        ui.Widget.call(this);
        //自定义属性color，定义按钮颜色
        this.defineAttr("color", (view, name, defaultGetter) => {
            return this._color;
        }, (view, name, value, defaultSetter) => {
            this._color = value;
            view.attr("backgroundTint", value);
        });
        //自定义属性onClick，定义被点击时执行的代码
        this.defineAttr("onClick", (view, name, defaultGetter) => {
            return this._onClick;
        }, (view, name, value, defaultSetter) => {
            this._onClick = value;
        });
    }
    ColoredButton.prototype.render = function () {
        return (
            <button textSize="16sp" style="Widget.AppCompat.Button.Colored" w="*" h="55" id="login" />
        );
    }
    ColoredButton.prototype.onViewCreated = function (view) {
        view.on("click", () => {
            if (this._onClick) {
                eval(this._onClick);
            }
        });
    }
    ui.registerWidget("colored-button", ColoredButton);
    return ColoredButton;
})();
var s = false;
var popWindow = ""
var storage = storages.create("data");
var systemInfo = {}
var deviceInfo = {}
var taskStatus = false
var mainActivityClassName = ""
function showWindow() {
    popWindow = floaty.rawWindow(
        <relative w="*" h="100" id="relative">
            <frame id="parent" w="*" h="100" />
            <frame id="child" width="250" height="100"
                layout_alignParentRight="true"
                layout_alignParentTop="true"
                alpha="0.7">
                <horizontal w="*" h="*">
                    <frame w="200" h="100" bg="#ffffff">
                        <text id="text" singleLine="false" color="#000000" size="12" padding="10" w="*" h="*" /><text />
                    </frame>
                    <button id="btn" text="关闭" w="50" h="100" />
                </horizontal>
            </frame>
        </relative>
    );
    popWindow.setSize(-1, -2)
    // popWindow.exitOnClose();
    // popWindow.relative.click(() => {
    //     popWindow.setAdjustEnabled(!popWindow.isAdjustEnabled());
    // });
    popWindow.btn.click(() => {
        clearActive()
    })
}
ui.layout(
    <vertical>
        <text text="大红花" textSize="20sp" textStyle="bold" textColor="black" gravity="center" margin="100" />
        <linear padding="30 0 30 0" marginBottom="20" id="linear1">
            <text w="56" gravity="center" color="#111111" size="16">账号</text>
            <input w="*" id="name" singleLine="true" hint="请输入账户" text="" />
        </linear>
        <linear padding="30 0 30 0" marginBottom="20">
            <text w="56" gravity="center" color="#111111" size="16">密码</text>
            <input w="*" id="password" password="true" hint="请输入密码" text="" />
        </linear>
        <frame padding="30 0 30 0" marginBottom="20">
            <colored-button text="登录" onClick="login()" color="black" />
            <progressbar id="loading" h="50" />
        </frame>
        <linear marginBottom="20" padding="30 0 30 0">
            <horizontal w="*">
                <text id="uuid" layout_weight="1" color="#111111" size="16"></text>
            </horizontal>
        </linear>
        <linear marginBottom="20" padding="30 0 30 0">
            <horizontal w="*">
                <text id="version" layout_weight="1" color="#111111" size="16"></text>
                <text id="brand" layout_weight="1" color="#111111" size="16"></text>
                <text id="model" layout_weight="1" color="#111111" size="16"></text>
            </horizontal>
        </linear>
        <frame padding="30 0 30 0" marginBottom="20">
            <button textSize="16sp" w="*" h="55" id="clear" text="停止脚本" />
        </frame>
    </vertical>
)
let loaginBtn = ui.login
let loading = ui.loading
function switchBtn(flage,callback) {
    ui.run(() => {
        loaginBtn.setVisibility(flage ? android.view.View.GONE : android.view.View.VISIBLE)
        loading.setVisibility(flage ? android.view.View.VISIBLE : android.view.View.GONE)
        if(callback){
            callback()
        }
    })
}
ui.run(() => {
    loading.setVisibility(android.view.View.GONE)
    // 读到缓存
    let localSystemInfo = storage.get('systemInfo')
    if (localSystemInfo) {
        systemInfo = localSystemInfo
        deviceInfo = storage.get('deviceInfo')
        setTimeout(() => {
            switchBtn(false)
            showMenu()
        }, 500);
    }
})
function clear(time) {
    toast('脚本已停止')
    if(time){
        storage.remove('systemInfo')
        startUiInit()
        return
    }
    setTimeout(() => {
        // threads.start(()=>{
        //     threads.exitAll()
        // })
        exit()
    }, 500);
}
function clearActive() {
    //test
    Xhs.clearTask()
    threads.start(function () {
        app.startActivity({
            packageName: 'com.dahongshu.app',
            className: mainActivityClassName,
            flags: [Intent.FLAG_ACTIVITY_NEW_TASK] // 可选标志，确保新任务  
        });
    })
    setTimeout(() => {
        toast('脚本已停止运行')
        popWindow.close();
        switchBtn(false)
        popWindow = ''
    }, 500);
}
function bindDevice() {
    let info = {
        "model": device.model,
        "brand": device.brand,
        "uuid":  device.getAndroidId(),
        "app_version": app.versionCode
    }
    deviceInfo = info
    ui.run(() => {
        ui.model.setText('型号：' + info.model)
        ui.brand.setText('品牌：' + info.brand)
        ui.uuid.setText('uuid：' + info.uuid)
    })
    Api.bindDevice(info, (res) => {
        if (res) {
            deviceInfo['mobile_id'] = res.mobile_id || ''
            deviceInfo['xhsid'] = res.xhsid || ''
            storage.put('deviceInfo', deviceInfo)
        }
    })
}
// 获取版本信息
function getSystemVersion() {
    Api.getVersion({}, (res) => {
        if (res) {
            systemInfo['url'] = res[0];
            systemInfo['version'] = res[1];
            if (!ui.version) {
                return
            }
            ui.run(() => {
                ui.version.setText('版本V' + res[1])
            })
        }
    })
    bindDevice()
}
getSystemVersion()


function showMenu(info) {
    toast('登录成功')
    let showInfo = [
        { name: '登录账户：', key: 'user_name' },
        { name: '登录时间：', key: 'start_time' },
        { name: '软件到期时间：', key: 'end_time' },
        { name: '当前版本：', key: 'app_version' },
        { name: '最新版本：', key: 'version' },
        { name: '型号：', key: 'brand' },
        { name: '品牌：', key: 'model' },
        { name: 'uuid唯一标识码：', key: 'uuid' },
        { name: '账户关联小红书号:', key: 'xhsid' },
    ]
    ui.run(function () {
        // 创建一个文本视图并设置其属性
        let layout = ui.layout(
            <vertical>
                <text text="大红花" textSize="20sp" textStyle="bold" textColor="black" gravity="center" margin="100" />
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[0].name} {systemInfo[showInfo[0].key]}</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[1].name} {systemInfo[showInfo[1].key]}</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[2].name} ------</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[3].name} v{deviceInfo[showInfo[3].key]}</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10" id="update">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[4].name} v{systemInfo[showInfo[4].key]} 点击可自动下载更新</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[5].name} {deviceInfo[showInfo[5].key]}</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[6].name} {deviceInfo[showInfo[6].key]}</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[7].name} {deviceInfo[showInfo[7].key]}</text>
                </linear>
                <linear padding="30 0 30 0" marginBottom="10">
                    <text w="*" color="black" size="14" textStyle="bold">{showInfo[8].name} {deviceInfo[showInfo[8].key]}</text>
                </linear>
                <frame padding="30 0 30 0" margin="0 20 0 20" id="login">
                    <colored-button text="启动脚本" onClick="startTask()" color="black" />
                </frame>

                <frame padding="30 0 30 0" margin="0 20 0 20" id="loading" visibility="gone">
                    <progressbar h="80" />
                    <text w="*" color="black" size="14" textStyle="bold" gravity="center">运行中</text>
                </frame>
                <frame padding="30 0 30 0" marginBottom="20">
                    <colored-button text="退出登录" onClick="clear(true)" color="#cccccc" />
                </frame>
                <frame padding="30 0 30 0" marginBottom="20">
                    <colored-button text="停止脚本" onClick="clear()" color="#cccccc" />
                </frame>
            </vertical>
        );
        setTimeout(() => {
            loaginBtn = ui.login
            loading = ui.loading
            if (ui.update) {
                ui.update.on("click", () => {
                    confirm('即将前往最新下载地址').then((res) => {
                        if (res) {
                            app.openUrl(systemInfo['url'])
                        }
                    })
                })
            }
        }, 500);
    })
}
function login() {
    let name = (ui.name.getText() + '').trim()
    let password = (ui.password.getText() + '').trim()
    
    if (name && password) {
        switchBtn(true)
        Api.toLogin({
            username: name,
            password: password
        }, (res) => {
            if (res) {
                console.log('res.token' + res.token + 'res.app_id' + res.app_id);
                systemInfo['token'] = res.token
                systemInfo['app_id'] = res.app_id
                systemInfo['user_name'] = name
                systemInfo['start_time'] = Comman.getDate()
                setTimeout(() => {
                    storage.put('systemInfo', systemInfo)
                    showMenu()
                }, 500);
                return
            }
            switchBtn(false)
        })
    } else {
        toast('账户或密码不能为空')
    }
}
if (ui.clear) {
    ui.clear.on("click", () => clear())
}
function startTask() {
    mainActivityClassName = currentActivity()
    device.keepScreenOn()
    try {
        auto() // 无障碍处理
        // 文件读写权限
        switchBtn(true,()=>{
            if (!App.hasStoragePermission()) {
                confirm('请开启文件读写权限')
                switchBtn(false)
                return
            }
            let ram = device.getAvailMem() / 1000 / 1000 / 1000
            if (ram < 0.5) {
                confirm('当前内存严重不足，请释放后台后再运行')
                switchBtn(false)
                return
            }
            Xhs.packName = app.getPackageName('小红书') || 'com.xingin.xhs'
            Xhs.AppPackName = app.getPackageName('大红书') || "org.autojs.autojs"
            confirm('确认小红书打开对应全部权限，并登录设备绑定账户，避免功能使用出错').then((val) => {
                if (val) {
                    Api.getTask({}, (res) => {
                        // if(!deviceInfo['xhsid']){
                        //     confirm('请先前往后台进行设备与小红书账号绑定')
                        //     return
                        // }
                        if (res) {
                            threads.start(function () {
                                showWindow()
                                Xhs.init()
                            })
                        }else{
                            switchBtn(false)
                        }
                    })
                } else {
                    switchBtn(false)
                }
            })
        })
    } catch (error) {
        confirm('如果无法解决问问，可能是安卓的BUG，您可能需要重启手机或重启设置中无障碍服务')
    }
}
//登录事件
function startUiInit() {
    console.log('startUiInit');
    ui.run(() => {
        ui.layout(
            <vertical>
                <text text="大红花" textSize="20sp" textStyle="bold" textColor="black" gravity="center" margin="100" />
                <linear padding="30 0 30 0" marginBottom="20" id="linear1">
                    <text w="56" gravity="center" color="#111111" size="16">账号</text>
                    <input w="*" id="name" singleLine="true" hint="请输入账户" text="" />
                </linear>
                <linear padding="30 0 30 0" marginBottom="20">
                    <text w="56" gravity="center" color="#111111" size="16">密码</text>
                    <input w="*" id="password" password="true" hint="请输入密码" text="" />
                </linear>
                <frame padding="30 0 30 0" marginBottom="20">
                    <colored-button text="登录" onClick="login()" color="black" />
                    <progressbar id="loading" h="50" />
                </frame>
                <linear marginBottom="20" padding="30 0 30 0">
                    <horizontal w="*">
                        <text id="uuid" layout_weight="1" color="#111111" size="16"></text>
                    </horizontal>
                </linear>
                <linear marginBottom="20" padding="30 0 30 0">
                    <horizontal w="*">
                        <text id="version" layout_weight="1" color="#111111" size="16"></text>
                        <text id="brand" layout_weight="1" color="#111111" size="16"></text>
                        <text id="model" layout_weight="1" color="#111111" size="16"></text>
                    </horizontal>
                </linear>
                <frame padding="30 0 30 0" marginBottom="20">
                    <button textSize="16sp" w="*" h="55" id="clear" text="停止脚本" />
                </frame>
            </vertical>
        )
        setTimeout(() => {
            ui.loading.setVisibility(android.view.View.GONE)
            loaginBtn = ui.login
            loading = ui.loading
            getSystemVersion()
            if (ui.clear) {
                ui.clear.on("click", () => clear())
            }
        }, 500);
    })
}

module.exports = {
    setTopText(desc) {
        ui.run(function () {
            let oldDesc = (popWindow.text.getText() + "\n").split("\n");
            oldDesc = oldDesc.filter((item) => item.trim() !== '')
            let oldDescFormat = oldDesc.slice(-1).map((item) => item + '\n').join('')
            popWindow.text.setText(oldDescFormat + desc);
        });
    },
    startInit() {
        storage.remove('systemInfo')
        startUiInit()
    },
    setTouchable(flase) {
        popWindow.setTouchable(flase)
    },
    systemInfo: systemInfo,
    deviceInfo: deviceInfo,
    mainActivityClassName: mainActivityClassName
}